<template>
  <div class="interface-analysis">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon total-icon">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalInvokes }}</div>
              <div class="stats-label">总调用次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon today-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.todayInvokes }}</div>
              <div class="stats-label">今日调用</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon success-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.successRate }}%</div>
              <div class="stats-label">成功率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon avg-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.avgResponseTime }}ms</div>
              <div class="stats-label">平均响应时间</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>调用趋势</span>
              <el-select v-model="trendPeriod" size="small" style="width: 120px">
                <el-option label="最近7天" value="7" />
                <el-option label="最近30天" value="30" />
                <el-option label="最近90天" value="90" />
              </el-select>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>接口调用排行</span>
            </div>
          </template>
          <div ref="rankingChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>接口调用详情</span>
          <el-button type="primary" @click="exportData">导出数据</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="name" label="接口名称" min-width="150" />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)">{{ row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalInvokes" label="总调用次数" width="120" sortable />
        <el-table-column prop="successInvokes" label="成功次数" width="120" sortable />
        <el-table-column prop="successRate" label="成功率" width="100">
          <template #default="{ row }">
            <el-progress
              :percentage="row.successRate"
              :color="getProgressColor(row.successRate)"
              :show-text="false"
            />
            <span style="margin-left: 8px">{{ row.successRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="avgResponseTime" label="平均响应时间" width="140" sortable>
          <template #default="{ row }">
            {{ row.avgResponseTime }}ms
          </template>
        </el-table-column>
        <el-table-column prop="lastInvokeTime" label="最后调用时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataLine, 
  TrendCharts, 
  CircleCheck, 
  Timer 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 统计数据
const stats = ref({
  totalInvokes: 123456,
  todayInvokes: 1234,
  successRate: 98.5,
  avgResponseTime: 245
})

// 图表数据
const trendPeriod = ref('7')
const trendChartRef = ref()
const rankingChartRef = ref()

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const typeMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return typeMap[method] || 'info'
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 70) return '#e6a23c'
  return '#f56c6c'
}

// 初始化趋势图表
const initTrendChart = () => {
  const chart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['调用次数', '成功次数', '失败次数']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '调用次数',
        type: 'line',
        smooth: true,
        data: [1200, 1800, 2200, 2800, 3200, 3800, 4200],
        itemStyle: { color: '#409eff' }
      },
      {
        name: '成功次数',
        type: 'line',
        smooth: true,
        data: [1180, 1750, 2150, 2750, 3150, 3750, 4150],
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '失败次数',
        type: 'line',
        smooth: true,
        data: [20, 50, 50, 50, 50, 50, 50],
        itemStyle: { color: '#f56c6c' }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化排行图表
const initRankingChart = () => {
  const chart = echarts.init(rankingChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['用户管理', '文件上传', '数据分析', '消息通知', '其他接口']
    },
    series: [
      {
        name: '调用次数',
        type: 'bar',
        data: [3200, 2800, 2200, 1800, 1200],
        itemStyle: {
          color: function(params) {
            const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
            return colors[params.dataIndex]
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: '获取用户信息',
        method: 'GET',
        totalInvokes: 3200,
        successInvokes: 3150,
        successRate: 98.4,
        avgResponseTime: 120,
        lastInvokeTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '文件上传',
        method: 'POST',
        totalInvokes: 2800,
        successInvokes: 2750,
        successRate: 98.2,
        avgResponseTime: 350,
        lastInvokeTime: '2024-01-15 09:15:00'
      },
      {
        id: 3,
        name: '数据分析',
        method: 'POST',
        totalInvokes: 2200,
        successInvokes: 2150,
        successRate: 97.7,
        avgResponseTime: 580,
        lastInvokeTime: '2024-01-15 08:45:00'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getTableData()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 查看详情
const viewDetail = (row) => {
  ElMessage.info(`查看 ${row.name} 的详细数据`)
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出成功')
}

// 监听趋势周期变化
watch(trendPeriod, () => {
  initTrendChart()
})

onMounted(async () => {
  await nextTick()
  initTrendChart()
  initRankingChart()
  getTableData()
})
</script>

<style scoped lang="scss">
.interface-analysis {
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stats-card {
    .stats-content {
      display: flex;
      align-items: center;
      
      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
        
        &.total-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.today-icon {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.success-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.avg-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
      
      .stats-info {
        .stats-number {
          font-size: 24px;
          font-weight: 600;
          color: #333;
          line-height: 1;
        }
        
        .stats-label {
          font-size: 14px;
          color: #666;
          margin-top: 4px;
        }
      }
    }
  }
  
  .charts-row {
    margin-bottom: 20px;
  }
  
  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      height: 300px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
